<?php
namespace app\install\controller;

class Index extends \think\Controller
{
	function index(){
		$path=env('root_path').'/static/upload/install/';
		if (file_exists($path.'install.lock')) {
		    echo '
		        <html>
		        <head>
		        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
		        </head>
		        <body style="text-align:center;color:red;">
		            你已经安装过该系统，如果想重新安装，请先删除站点static/upload/install目录下的 install.lock 文件，然后再安装。
		        </body>
		        </html>';
		    exit;
		}
		
		
		if ($this->request->isAjax()) {
			$data_str=\file_get_contents($path.'database.txt');
			$data=input('post.');
			$data_str= $this->display($data_str,$data,['layout_on'=>false])->getContent();
			\file_put_contents(env('root_path')."/config/database.php","<?php ".PHP_EOL.$data_str);
			 
			$sql=\file_get_contents($path.'database.sql');
			$sql=\str_replace("kp_",$data['prefix'],$sql);
			 
			
			$dsn="mysql:host={$data['hostname']}".($data['hostport']?":".$data['hostport']:'').";dbname={$data['database']}";
			$db = new \PDO($dsn, $data['username'], $data['password']); 
			$db->query('set names utf8;'); 
			$db->query($sql);
			$sql="TRUNCATE `{$data['prefix']}admin`; INSERT INTO `{$data['prefix']}admin`(name,pass) VALUES ('{$data['admin_name']}', '".\sha1($data['admin_pass'])."');";
			$db->query($sql);
            $db = null;
			\file_put_contents($path."install.lock",'');
		    $this->success("安装成功", "/admin.php");
		}
		return view();
	}
}
